using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameManager : MonoBehaviour
{
    [SerializeField] private IconHandler iconHandler;
    [SerializeField] private GameObject restartGameObject;
    [SerializeField] private SlingShotHandler slingShotHandler;
    public static GameManager instance;
    public int maxNumberOfShots = 3;
    private int usedNumberOfShots = 0;
    private readonly List<Baddie> piggies = new();

    private void Awake()
    {
        if (instance == null) instance = this;
        // 将所有小猪添加到List合集
        Baddie[] allPiggies = FindObjectsOfType<Baddie>();
        for (int i = 0; i < allPiggies.Length; i++)
        {
            piggies.Add(allPiggies[i]);
        }
    }
    // 删除小猪合集与游戏对象
    public void DestroyPiggie(Baddie piggie)
    {
        if (piggies != null)
        {
            piggies.Remove(piggie);
            Destroy(piggie.gameObject);
            CheckGameState();
        }
    }
    public void UseShot()
    {
        // 发射小鸟之后 使用次数增加 改变图标
        usedNumberOfShots++;
        iconHandler.UseShot(usedNumberOfShots);
    }
    // 检查是否还能发射小鸟
    public bool HasEnoughShots()
    {
        return usedNumberOfShots < maxNumberOfShots;
    }

    // 游戏输赢检查
    public void CheckGameState()
    {
        // 没有猪 游戏胜利
        if (piggies.Count <= 0)
        {
            WinGame();
        }
        // 还有猪与无法射击 游戏失败
        else if (!HasEnoughShots() && piggies.Count >= 0)
        {
            RestartGame();
        }
    }
    // 游戏胜利
    private void WinGame()
    {
        restartGameObject.SetActive(true);
        slingShotHandler.enabled = false;
    }
    // 游戏失败
    public void RestartGame()
    {
        SceneManager.LoadScene("SampleScene");
    }
}
